package com.songlanyun.common.utils;

import com.songlanyun.common.utils.sensi.BaseMsgXml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.util.Map;

public class XmlUtil {

    /**
     * 将XML字符串转为对象
     *
     * @param xml
     * @return com.syiti.dev.sssy.entity.TianYaHaiJiaoHttpResult
     * @author LinYoufeng
     * @date 16:14 2019/11/26
     **/
    public static <T> T xmlToBean(String xml, Class<T> load)  {
        try {
            JAXBContext context = JAXBContext.newInstance(load);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(xml));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String xml = "<xml><ToUserName><![CDATA[ww826edbe3ad695167]]></ToUserName><FromUserName><![CDATA[sys]]></FromUserName><CreateTime>1618981356</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[change_contact]]></Event><ChangeType><![CDATA[update_party]]></ChangeType><Id>5</Id><Name><![CDATA[产品3]]></Name></xml>";
        System.out.println(xmlToBean(xml, BaseMsgXml.class));
    }


}
